package org.javaboy.shiro.config;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.*;
import java.util.EnumSet;

public class WebInit implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(WebConfig.class);
        ctx.setServletContext(servletContext);
        ctx.refresh();
        ServletRegistration.Dynamic springmvc = servletContext.addServlet("springmvc", new DispatcherServlet(ctx));
        springmvc.addMapping("/");

        /**
         * DelegatingFilterProxy 实际上是一个代理过滤器，这个过滤器会把请求拦截下来，拦截下来之后，根据 targetBeanName 属性去 Spring 容器中查找同名的 Filter，然后将拦截下来的请求交给这个 Filter 去处理。
         * 如果我们没有配置 targetBeanName，那么就去 Spring 容器中找和当前 Filter 同名的 Bean 去处理当前请求
         */
        FilterRegistration.Dynamic shiroFilterFactoryBean = servletContext.addFilter("xxx", new DelegatingFilterProxy("shiroFilterFactoryBean", ctx));
        shiroFilterFactoryBean.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");
    }
}
